<template>
  <div>
    <Content>
		<div id="graphContainer"></div>
    </Content>
  </div>
</template>

<script>
	import './graph/Init';
	import mxgraph from './graph/index';
	import Toolbar from './graph/Toolbar';
	import EditorUi from './graph/EditorUi';
	import Editor from './graph/Editor';
	import './graph/Shapes';
	import UrlParams from './graph/UrlParams';
	import {Menus} from './graph/Menus';
	import grapheditorTxt from './resources/grapheditor.txt';
	import defaultXml from './styles/default.xml';
	import graphApi from '../../api/graph.api'

	const {
	  mxGraph,
	  mxOutline,
	  mxEvent,
	  mxCell,
	  mxGeometry,
	  mxUtils,
	  mxEventObject,
	  mxConnectionHandler,
	  mxRubberband,
	  mxToolbar,
	  mxResources,
	  mxCodec,
	} = mxgraph;

  import { Graph } from './graph/Graph';
	export default {
		name: 'Grapheditor',

		data() {
	    return {
	      id: '',
	      name: '',
	      xml: '',
	    };
	 	},

	  components: {
	  },

	  computed: {
	  },

	  methods: {
	  	init() {
	  		let self = this;
	  		let editorUiInit = EditorUi.prototype.init;
	  		EditorUi.prototype.init = function() {
				editorUiInit.apply(this, arguments);
				// Updates action states which require a backend
				this.actions.get('open').setEnabled(true);
			};

			// Adds required resources (disables loading of fallback properties, this can only
			// be used if we know that all keys are defined in the language specific file)
			mxResources.loadDefaultBundle = false;
			mxResources.parse(grapheditorTxt);
	
			// Configures the default graph theme
			var themes = new Object();
			themes[Graph.prototype.defaultThemeName] = mxUtils.parseXml(defaultXml).documentElement; 
			
			// Main
			let mEditorUi = new EditorUi(new Editor(UrlParams['chrome'] == '0', themes), document.getElementById('graphContainer'));
			let mGraph = mEditorUi.editor.graph;

			if(self.xml) {
				mEditorUi.editor._id = self.id;
				mEditorUi.editor.filename = self.name;
				mGraph.getModel().beginUpdate();
			    try {
			      const doc = mxUtils.parseXml(self.xml);
			      const root = doc.documentElement;
			      const dec = new mxCodec(root.ownerDocument);
			      dec.decode(root, mGraph.getModel());
			    } finally {
			      mGraph.getModel().endUpdate();
			    }
		    }

		    Object.values(mGraph.getModel().cells).forEach(cell => {debugger;
				if (cell.vertex && cell.data) {
				  cell.data = JSON.parse(cell.data);
				  console.log(cell.data);
				}
			});
	  	},
	  },

	  created() {

	  },

	  mounted() {
	    if(this.$route.params.hasOwnProperty('id')) {
	  		this.id = this.$route.params.id;
	  		graphApi.fetchData(this.id).then(res=>{
	  			let data = res.data.data;
	  			this.name = data.name
	  			this.xml = data.xml;
	  			this.init();
	  		})
	  	} else {
	  		this.init();
	  	}
	  },

	  beforeDestroy() {
	  }
	}
</script>

<style scoped>
	@import "./styles/grapheditor.css";
</style>